﻿namespace com.game.module.login
{
    using com.game;
    using com.game.data;
    using com.game.manager;
    using com.game.module.core;
    using com.game.module.effect;
    using com.game.module.SystemData;
    using com.game.Public.Confirm;
    using com.game.Public.Message;
    using com.game.SDK;
    using com.game.sound;
    using com.game.start;
    using com.game.vo;
    using com.net;
    using com.net.interfaces;
    using com.u3d.bases.debug;
    using PCustomDataType;
    using Proto;
    using System;
    using System.Globalization;
    using System.IO;
    using System.Runtime.CompilerServices;
    using UnityEngine;

    public class LoginControl : BaseControl<LoginControl>
    {
        private bool _isCreateRole;
        public static float fPosY = 1.3f;
        private readonly byte[] heart;
        private float lastDelayTime;
        private float lastReceiveTime;
        private float lastSendTime;
        public static ulong myID;
        public string platformName;
        private uint reciveCount;
        public string[] roleList;
        private uint sendCount;
        private bool startMoviePlayed;

        public LoginControl()
        {
            byte[] buffer1 = new byte[4];
            buffer1[1] = 2;
            buffer1[2] = 1;
            this.heart = buffer1;
        }

        public void ChangeToFirstScene()
        {
            int dungeonId = int.Parse(Singleton<ConfigConst>.Instance.GetConfigDataString("NEW_GUIDE_DUPLICATE"));
            Singleton<DungeonMode>.Instance.enterDungeonCreateRole(dungeonId);
        }

        public bool CheckTimeOut()
        {
            if (this.maxdelay == 0)
            {
                this.maxdelay = 10;
            }
            return (this.getLastDelayTime() > this.maxdelay);
        }

        private void Fun_1_0(INetData data)
        {
            Log.info(this, "Receive HeartMsg");
            LoginHeartMsg_1_0 g__ = new LoginHeartMsg_1_0();
            g__.read(data.GetMemoryStream());
            ServerTime.Instance.Timestamp = (int) g__.serverTime;
            this.lastReceiveTime = RealTime.time;
            if (this.reciveCount < this.sendCount)
            {
                this.lastDelayTime = this.lastReceiveTime - this.lastSendTime;
                this.reciveCount++;
            }
        }

        private void Fun_1_1(INetData data)
        {
            LoginLoginMsg_1_1 g__ = new LoginLoginMsg_1_1();
            g__.read(data.GetMemoryStream());
            PLoginInfo[] infoArray = g__.loginInfo.ToArray();
            if (g__.code != 0)
            {
                Log.info(this, "-Fun_1_1 登陆失败！code:" + g__.code);
                if (g__.code == 12)
                {
                    Log.debug(this, "没有创建角色，进入角色创建界面");
                    Singleton<LoginPanel>.Instance.CloseView();
                    if (!this.startMoviePlayed)
                    {
                        this.startMoviePlayed = true;
                        this.OpenRoleCreateView(null);
                    }
                }
                else
                {
                    SysErrorCodeVo errorCodeVo = BaseDataMgr.instance.GetErrorCodeVo(uint.Parse(g__.code.ToString(CultureInfo.InvariantCulture)));
                    string desc = string.Empty;
                    if (errorCodeVo == null)
                    {
                        desc = string.Format("Errorcode {0} is not defined", g__.code);
                    }
                    else
                    {
                        desc = errorCodeVo.desc;
                    }
                    ConfirmMgr.Instance.ShowOkAlert(desc + ",退出游戏再试一次吧，亲~", "OK_CANCEL", new ClickCallback(this.QuitGame), LanguageManager.GetWord("ConfirmView.Ok"));
                }
            }
            else
            {
                Log.debug(this, "-Fun_1_1 登录成功，获取登陆角色信息:");
                for (int i = 0; i < infoArray.Length; i++)
                {
                    Log.debug(this, "id: " + infoArray[i].id);
                    Log.debug(this, "name: " + infoArray[i].name);
                    Log.debug(this, "job: " + infoArray[i].job);
                    Log.debug(this, "level: " + infoArray[i].level);
                    Log.debug(this, "sex id: " + infoArray[i].sex);
                    Log.debug(this, "lastLoginTime: " + infoArray[i].lastLoginTime);
                    Log.debug(this, "serverId: " + infoArray[i].serverId);
                }
                Log.debug(this, "-Fun_1_1 默认选择第一个游戏角色进入游戏");
                MeVo.instance.Id = infoArray[0].id;
                myID = MeVo.instance.Id;
                MeVo.instance.Name = infoArray[0].name;
                MeVo.instance.job = infoArray[0].job;
                MeVo.instance.Level = infoArray[0].level;
                MeVo.instance.sex = infoArray[0].sex;
                MeVo.instance.lastLoginTime = infoArray[0].lastLoginTime;
                MeVo.instance.serverId = infoArray[0].serverId;
                MemoryStream msdata = new MemoryStream();
                Module_1.write_1_2(msdata, MeVo.instance.Id, GlobalData.sign);
                AppNet.gameNet.send(msdata, 1, 2);
                SoundMgr.Instance.PlaySceneAudio("1000");
            }
        }

        private void Fun_1_2(INetData data)
        {
            LoginSelectRoleMsg_1_2 g__ = new LoginSelectRoleMsg_1_2();
            g__.read(data.GetMemoryStream());
            if (g__.code == 1)
            {
                Debug.Log("断线重连！！！！！！！！！！！！！！！！！");
            }
            else if (g__.code > 1)
            {
                ErrorCodeManager.ShowError(g__.code);
                if (g__.code == 0x6c)
                {
                    Log.debug(this, "-Fun_1_2账号被锁定，锁定时间：" + g__.time);
                }
            }
            else
            {
                Log.debug(this, "-Fun_1_2 创建角色成功，获取角色信息(默认选择第一个角色作为本玩家选择的角色)");
                PRole role = g__.role.ToArray()[0];
                MeVo.instance.Id = role.id;
                MeVo.instance.Name = role.name;
                MeVo.instance.sex = role.sex;
                MeVo.instance.Level = role.level;
                MeVo.instance.job = role.job;
                MeVo.instance.mapId = role.mapId;
                MeVo.instance.X = role.x * 0.001f;
                MeVo.instance.Y = role.y * 0.001f;
                MeVo.instance.Z = role.z * 0.001f;
                MeVo.instance.toX = MeVo.instance.X;
                MeVo.instance.toY = MeVo.instance.Y;
                MeVo.instance.toZ = MeVo.instance.Z;
                MeVo.instance.needEnterDuplicate = g__.newbieDuplicate == 1;
                Log.debug(this, "-Fun_1_2选择角色进入场景：");
                Log.debug(this, "选择人物mapId: " + MeVo.instance.mapId);
                Log.debug(this, "选择人物X坐标: " + MeVo.instance.X);
                Log.debug(this, "选择人物Y坐标: " + MeVo.instance.Y);
                this.LoginSuccess();
            }
        }

        private void Fun_1_3(INetData data)
        {
            LoginCreateRoleMsg_1_3 g__ = new LoginCreateRoleMsg_1_3();
            g__.read(data.GetMemoryStream());
            if (g__.code != 0)
            {
                ErrorCodeManager.ShowError(g__.code);
            }
            else
            {
                this._isCreateRole = true;
                Log.info(this, "-Fun_1_3() 创建角色成功！角色ID：" + g__.id);
                MeVo.instance.Id = g__.id;
                SDKManager.SDKCreateRoleLog(Singleton<RoleMode>.Instance.roleName, Singleton<LoginMode>.Instance.serverId.ToString());
                Singleton<LoginPanel>.Instance.CloseView();
            }
        }

        private void Fun_1_4(INetData data)
        {
        }

        private void Fun_1_6(INetData data)
        {
            LoginClientInfoMsg_1_6 g__ = new LoginClientInfoMsg_1_6();
            g__.read(data.GetMemoryStream());
            if (g__.code != 0)
            {
                ErrorCodeManager.ShowError(g__.code);
            }
        }

        private void Fun_1_8(INetData data)
        {
            LoginLoginKeyMsg_1_8 g__ = new LoginLoginKeyMsg_1_8();
            g__.read(data.GetMemoryStream());
            GlobalData.SetSign(g__.loginKey);
        }

        public float getLastDelayTime()
        {
            if (this.sendCount == this.reciveCount)
            {
                return this.lastDelayTime;
            }
            float num = RealTime.time - this.lastSendTime;
            if (num < this.lastDelayTime)
            {
                return this.lastDelayTime;
            }
            return num;
        }

        public void LoginSuccess()
        {
            Log.info(this, "serverId:" + Singleton<LoginMode>.Instance.serverId);
            Log.info(this, "serverInfo:" + Singleton<LoginPanel>.Instance.Info.Id);
            if (AppStart.RunMode != 0)
            {
                SDKManager.SDKCreateAssistant(Singleton<LoginMode>.Instance.serverId.ToString());
                SDKManager.SDKShowAssistant();
            }
            Singleton<AchievementMode>.Instance.ApplyAchieveInfo();
            Singleton<GeneralMode>.Instance.ApplyGenralListInfo();
            Singleton<BagControl>.Instance.RequestItemInfo(1);
            Singleton<BagControl>.Instance.RequestItemInfo(2);
            if (!this._isCreateRole && !MeVo.instance.needEnterDuplicate)
            {
                Singleton<MapMode>.Instance.changeScene_4_2();
            }
            else if (MeVo.instance.needEnterDuplicate && !this._isCreateRole)
            {
                vp_Timer.In(1.5f, new vp_Timer.Callback(this.ChangeToFirstScene), null);
            }
            else
            {
                this._isCreateRole = false;
                Singleton<RoleCreateView>.Instance.CloseView();
            }
            Singleton<LoginMode>.Instance.loginSuc = true;
            Singleton<LoginPanel>.Instance.CloseView();
            Singleton<SelectServerView>.Instance.CloseView();
            Singleton<UpdateAnnounceControl>.Instance.GetAnnounce();
            Singleton<DungeonMode>.Instance.getDungeonList();
            Singleton<DungeonMode>.Instance.ReqChapterStarAwardInfo();
            Singleton<MapMode>.Instance.InitMapCameraData();
            Singleton<SystemSettingsMode>.Instance.GetAllSystemSettings();
            Singleton<MailMode>.Instance.RequestMailBasicInfo();
            Singleton<VIPMode>.Instance.ReqInitVipInfo();
            Singleton<GoldBoxMode>.Instance.GetGoldBuyInfo();
        }

        private void MovieStart1PlayFinish(GameObject go)
        {
            EffectMgr.Instance.CreateUIEffect("30034", Vector3.zero, new com.game.module.effect.Effect.EffectCallback(this.MovieStart2PlayFinish), null);
        }

        private void MovieStart1PlayStart()
        {
            EffectMgr.Instance.CreateUIEffect("30028", Vector3.zero, new com.game.module.effect.Effect.EffectCallback(this.MovieStart1PlayFinish), new com.game.module.effect.Effect.EffectCreateCallback(this.PlayStartMovieMusic));
        }

        private void MovieStart2PlayFinish(GameObject go)
        {
            EffectMgr.Instance.CreateUIEffect("30035", Vector3.zero, new com.game.module.effect.Effect.EffectCallback(this.OpenRoleCreateView), null);
        }

        protected override void NetListener()
        {
            AppNet.main.addCMD("256", new NetMsgCallback(this.Fun_1_0));
            AppNet.main.addCMD("257", new NetMsgCallback(this.Fun_1_1));
            AppNet.main.addCMD("258", new NetMsgCallback(this.Fun_1_2));
            AppNet.main.addCMD("259", new NetMsgCallback(this.Fun_1_3));
            AppNet.main.addCMD("260", new NetMsgCallback(this.Fun_1_4));
            AppNet.main.addCMD("262", new NetMsgCallback(this.Fun_1_6));
            AppNet.main.addCMD("264", new NetMsgCallback(this.Fun_1_8));
        }

        private void OpenRoleCreateView(GameObject go)
        {
            SoundMgr.Instance.StopAll();
            SoundMgr.Instance.PlaySceneAudio("1000");
            Singleton<RoleCreateView>.Instance.OpenView();
        }

        private void PlayStartMovieMusic(EffectControlerII controller)
        {
            SoundMgr.Instance.PlaySceneAudio("1017");
        }

        private void QuitGame()
        {
            Application.Quit();
        }

        public void ResetHeartBeatState()
        {
            this.lastDelayTime = 0f;
            this.lastSendTime = 0f;
            this.lastReceiveTime = 0f;
            this.sendCount = 0;
            this.reciveCount = 0;
        }

        public void SendHeartMsg()
        {
            float time = RealTime.time;
            if (this.heartGap == 0)
            {
                this.heartGap = 5;
            }
            if ((this.sendCount == this.reciveCount) && ((time - this.lastSendTime) >= this.heartGap))
            {
                Log.info(this, "Send HeartMsg");
                MemoryStream msdata = new MemoryStream();
                Module_1.write_1_0(msdata);
                AppNet.gameNet.send(msdata, 1, 0);
                this.lastSendTime = time;
                this.sendCount++;
            }
            else if (this.lastSendTime > time)
            {
                this.lastSendTime = time;
            }
        }

        public void SendHeartMsgDirect()
        {
            MemoryStream msdata = new MemoryStream();
            Module_1.write_1_0(msdata);
            AppNet.gameNet.send(msdata, 1, 0);
            this.lastSendTime = RealTime.time;
            this.sendCount++;
        }

        public short heartGap { get; set; }

        public short maxdelay { get; set; }
    }
}

